package cn.bigway.app.weavingdesigner.util;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.JPanel;

public class WdImagePanel extends JPanel implements MouseWheelListener,
		MouseListener {

	private static final long serialVersionUID = 5646144890406699489L;

	private static final double MIN_ZOOM = 0.1;

	private double zoom;
	private Image image;
	private WdImageViewPanel imageViewPanel;

	public WdImagePanel(WdImageViewPanel imageViewPanel, Image image) {
		this.zoom = 1.0;
		this.image = image;
		this.imageViewPanel = imageViewPanel;
		setFocusable(true);
		addMouseListener(this);
		addMouseWheelListener(this);
	}

	@Override
	protected void paintComponent(Graphics g) {
		Graphics2D grp = (Graphics2D) g;
		grp.scale(this.zoom, this.zoom);
		grp.drawImage(this.image, 0, 0, this);
		grp.dispose();
	}

	@Override
	public Dimension getPreferredSize() {
		return new Dimension(
				(int) (this.image.getWidth(this) + (this.image.getWidth(this) * (this.zoom - 1))),
				(int) (this.image.getHeight(this) + (this.image.getHeight(this) * (this.zoom - 1))));
	}

	public void zoom(double value) {
		this.zoom += value;
		if (this.zoom < MIN_ZOOM) {
			this.zoom = MIN_ZOOM;
		}
		this.imageViewPanel.adjustLayout();
	}

	@Override
	public void mouseWheelMoved(MouseWheelEvent event) {
		zoom(event.getWheelRotation() * (event.isControlDown() ? 10.0 : 1.0)
				/ 10);
	}

	@Override
	public void mouseClicked(MouseEvent event) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mouseEntered(MouseEvent event) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mouseExited(MouseEvent event) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mousePressed(MouseEvent event) {
		if (event.getModifiers() == InputEvent.BUTTON2_MASK) {
			this.zoom = 1.0;
			this.imageViewPanel.adjustLayout();
		}
	}

	@Override
	public void mouseReleased(MouseEvent event) {
		// TODO Auto-generated method stub
	}
}
